<template>
  <div id="input-mode" @click="handleDocumentClick">
    <!-- 输入框 -->
    <el-input
      v-model="inputContent"
      style="width: 350px; height: 43px"
      placeholder="搜索位置、公交站、地铁站"
      id="input"
      :suffix-icon="Search"
      @focus="handleFocus"
      @input="handleSearchInputPOI"
    >
      <template #prefix>
        <!-- logo -->
        <div class="logo">
          <img
            src=""
            alt=""
          />
        </div>
      </template>
      <template #append>
        <!-- 切换按钮 -->
        <el-button
          class="navigation-btn"
          v-if="showBtn"
          @click="handleNavigation"
        >
          <i class="iconfont icon-luxian"></i>
        </el-button>
        <el-button class="clearMark-btn" v-else @click="handleClearMark">
          <i class="iconfont icon-chahao"></i>
        </el-button>
      </template>
    </el-input>
    <!-- 快速定位+历史记录面板 -->
    <Transition>
      <div id="tips-history-panel" v-show="showHistory">
        <!-- 上部提示面板 -->
        <div class="tips-panel">
          <div>
            <img
              src="https://a.amap.com/pc/static/img/search_food.png"
              alt=""
            />
            <span>美食</span>
          </div>
          <div>
            <img
              src="https://a.amap.com/pc/static/img/search_hotel.png"
              alt=""
            />
            <span>酒店</span>
          </div>
          <div>
            <img
              src="https://a.amap.com/pc/static/img/search_view.png"
              alt=""
            />
            <span>景点</span>
          </div>
          <div>
            <img
              src="https://a.amap.com/pc/static/img/search_house.png"
              alt=""
            />
            <span>小区</span>
          </div>
        </div>
        <!-- 历史记录面板 -->
        <div id="history-panel">
          <ul v-if="searchHistory.length > 0">
            <li v-for="(item, index) in searchHistory" :key="index">
              <i class="iconfont icon-lishijilu"></i>
              <span @click="selectHistory(item)"> {{ item }}</span>
              <i class="iconfont icon-chahao" @click="removeHistory(index)"></i>
            </li>
          </ul>
          <div v-else class="no-history">暂无搜索记录</div>
          <button
            class="clear-history"
            @click="clearHistory"
            v-if="searchHistory.length > 0"
          >
            清空历史记录
          </button>
        </div>
      </div>
    </Transition>
    <!-- 导航面板 -->
    <Transition>
      <Navigation
        v-show="showNavigation"
        :show="showNavigation"
        @update:show="showNavigation = $event"
      ></Navigation>
    </Transition>
  </div>
  <!-- poi提示面板 -->
  <div id="outinput" v-show="showPoi">
    <ul>
      <li
        v-for="(item, index) in poiInfo"
        :key="index"
        @click="handleSelectPoi(item)"
      >
        <i class="iconfont icon-position"></i>
        <span v-html="highlightText(item.name, inputContent)"></span>
        <span>{{ item.address }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, inject, watchEffect, onMounted, onUnmounted } from 'vue';
import { Promotion, Search } from '@element-plus/icons-vue';
// 高德地图API加载
import AMapLoader from '@amap/amap-jsapi-loader';
import Navigation from './Navigation.vue';
// 注入
const { exmap } = inject('ex');

//⚠️控制切换按钮显示状态
const showBtn = ref(true);

// 输入框实时输入的内容
const inputContent = ref('');
// 控制记录显示隐藏
const showHistory = ref(false);
// 存储搜索记录
const searchHistory = ref([]);

// 控制poi提示面板显示隐藏
const showPoi = ref(false);
// 存储poi提示信息
const poiInfo = ref([]);

// 控制导航显示隐藏
const showNavigation = ref(false);

// 全局声明
let autoComplete;
let placeSearch;

onMounted(async () => {
  //✅获取历史记录 本地存储
  const savedHistory = localStorage.getItem('searchHistory');
  if (savedHistory) {
    searchHistory.value = JSON.parse(savedHistory);
  }
  //✅监听body点击事件->隐藏历史面板
  document.addEventListener('click', handleDocumentClick);

  // ==============🌸高德地图API加载与实例化===============
  // pi加载器
  window._AMapSecurityConfig = {
    securityJsCode: '3803fef5273a37c33f6c81666572c9c4',
  };
  // 异步加载高德地图API（等待API加载完成后，在创建底图实例map）
  const AMap = await AMapLoader.load({
    key: '73e59768fece08c22145999d58cdbb7d',
    version: '2.0',
    //引入的插件列表（与api加载器一同加载⚠️）
    plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch'],
  });

  // 创建 搜索提示实例
  autoComplete = new AMap.AutoComplete({
    city: '武汉',
    type: 'poi', // 返回结果类型，poi表示兴趣点
  });
  //自动动态监听地图实例
  watchEffect(() => {
    // 创建 地点跳转实例（⚠️因需添加到地图，需侦听）
    placeSearch = new AMap.PlaceSearch({
      city: '武汉',
      map: exmap.value,
      pageSize: 1, // 只返回一个结果
      extensions: 'all',
      /*   autoFitView: false, // 禁用自动调整视野（❗️核心配置） */
    });

    // 监听 PlaceSearch 的搜索完成事件，执行
    placeSearch.on('complete', function (result) {
      // 显示清楚覆盖物按钮
      showBtn.value = false;

      /*   // 监听 PlaceSearch 的搜索完成事件，设置视图级别
      exmap.value.setZoom(14);
      exmap.value.setCenter([
        result.poiList.pois[0].entr_location.lng,
        result.poiList.pois[0].entr_location.lat,
      ]); */
    });
    // 从列表选择poi点时触发
    /*  autoComplete.on('select', function (e) {
      //针对选中的poi实现自己的功能
      console.log('AutoComplete select 事件:', e);
      placeSearch.search(e.poi.name);
    }); */
  });
});

onUnmounted(() => {
  // 组件卸载时，移除事件监听，避免内存泄漏✅
  document.removeEventListener('click', handleDocumentClick);
  //新增对 autoComplete 的事件移除，优化内存管理
  if (autoComplete) {
    autoComplete.off('select');
  }
});

// =====================🌸功能性函数=====================
// ✅高亮显示提示 函数
const highlightText = (text, keyword) => {
  if (!keyword.trim()) return text;
  // 正则全局匹配，不区分大小写
  const regex = new RegExp(`(${keyword})`, 'gi');
  // 替换匹配内容为带highlight类的span
  return text.replace(regex, '<span class="highlight">$1</span>');
};

// ✅点击外部boay时：控制 历史记录面板+poi提示面板 关闭
const handleDocumentClick = (e) => {
  const inputEl = document.querySelector('#input-mode');
  // 点击目标在input外触发
  if (!inputEl.contains(e.target)) {
    showHistory.value = false;
    // 点击外部同时隐藏联想提示面板
    showPoi.value = false;
  }
};

// ======================🌸提示信息面板===================
// 👀点击清除搜索的 覆盖物
const handleClearMark = () => {
  showBtn.value = true;
  // 清除地图上的覆盖物
  exmap.value.clearMap();
  // 清除输入框内容
  inputContent.value = '';
};

//👀 输入时，提示面板逻辑
const handleSearchInputPOI = () => {
  // 0️⃣输入时，隐藏历史面板
  showHistory.value = false;

  // 1️⃣有输入内容则显示联想面板，无内容则隐藏
  const val = inputContent.value.trim();
  showPoi.value = val !== '';
  if (!val) {
    poiInfo.value = [];
    return;
  }
  //2️⃣调用 autoComplete.search 接口-》获取输入提示结果，并存储
  autoComplete.search(val, (status, result) => {
    if (status === 'complete' && result && result.tips) {
      console.log('AutoComplete 搜索结果:', result.tips);
      // 将联想结果存入自定义数组
      poiInfo.value = result.tips.map((tip) => ({
        name: tip.name,
        address: tip.district,
      }));
    } else {
      poiInfo.value = [];
      console.log('AutoComplete 搜索无结果或失败');
    }
  });
};

// 👀提示面板 选中项
const handleSelectPoi = (item) => {
  // 填充到输入框
  inputContent.value = item.name;
  // 隐藏提示信息面板
  showPoi.value = false;
  //定位至地点
  placeSearch.search(item.name);
  // 将选中内容加入搜索历史
  addToHistory(item.name);
};

// ======================🌸历史记录面板=============
// 0️⃣输入框聚焦，显示记录面板
const handleFocus = () => {
  showHistory.value = true;
};

//1️⃣将内容content存储到 历史记录（⚠️提示面板也用）
const addToHistory = (content) => {
  // 去重处理：如果已存在则移到最前面
  const index = searchHistory.value.indexOf(content);
  if (index !== -1) {
    searchHistory.value.splice(index, 1);
  }
  // 将搜索内容添加到记录数组的开头
  searchHistory.value.unshift(content);
  // 限制历史记录数量为8条
  if (searchHistory.value.length > 8) {
    // 移除数组的最后一个元素
    searchHistory.value.pop();
  }

  // 保存到本地存储✅
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

// 2️⃣选择历史记录项->填加到输入框
const selectHistory = (item) => {
  // 填充到输入框
  inputContent.value = item;
  // 跳转至地点
  placeSearch.search(item);
};

// 3️⃣清空历史记录
const clearHistory = () => {
  searchHistory.value = [];
  localStorage.removeItem('searchHistory'); // 同时清除本地存储
};

// 4️⃣删除选中的历史记录
const removeHistory = (index) => {
  searchHistory.value.splice(index, 1);
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

//====================🌸切换导航面版=============
const handleNavigation = () => {
  // 显示导航面板
  showNavigation.value = !showNavigation.value;
  // 关闭历史面板
  showHistory.value = false;
};
</script>

<style lang="scss" scoped>
@import '//at.alicdn.com/t/c/font_4989585_9nf5ibzq06o.css';
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
// 动画
.v-enter-active {
  transition: all 0.3s ease-out; /* 淡入时间和缓动效果 */
}
.v-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1); /* 缩短移出时间至0.2s实现快速移出 */
}
.v-enter-from,
.v-leave-to {
  transform: translateY(20px); /* 将X轴变换改为Y轴变换，实现上下方向动画 */
  opacity: 0;
}

#input-mode {
  position: absolute;
  top: 17.5px;
  left: 21px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 34px;
      height: 34px;
    }
  }
  .navigation-btn {
    i {
      font-size: 18px;
      font-weight: bold;
      color: #2c9eff;
    }
  }
  #tips-history-panel {
    position: absolute;
    width: 350px;
    background-color: white;
    top: 43px;
    left: 0px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
    // 上部快速定位
    .tips-panel {
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      width: 100%;
      height: 85px;
      border-bottom: 1px dashed #dbdee2;
      div {
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        align-items: center;
        img {
          width: 44px;
          height: 44px;
        }
        span {
          font-size: 14px;
          color: #6a788c;
        }
      }
    }
    // 历史记录面板
    #history-panel {
      margin-top: 6px;
      display: flex;
      flex-direction: column;
      align-items: center;
      ul {
        width: 90%;
        margin-bottom: 5px;
        li {
          margin: 2px 0;
          color: #9b9faf;
          display: flex;
          span {
            font-size: 14px;
            flex: 1;
          }
          i {
            font-size: 12px;
            width: 20px;
            padding-top: 5px;
          }
        }
      }
      .clear-history {
        border-bottom: none;
        border-left: none;
        border-right: none;
        border-top: 1px solid #9b9faf;
        background: none;
        color: #2c9eff;
        font-size: 15px;
        padding: 7px 0;
        width: 100%;
      }
      .no-history {
        color: #9b9faf;
        margin: 6px 0;
      }
    }
  }
}

#outinput {
  position: absolute;
  top: 60.5px;
  left: 21.5px;
  background-color: white;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  width: 349px;
  border-radius: 3px;
  ul {
    display: flex;
    flex-direction: column;
    gap: 9px;
    padding: 9px 9px;
    li {
      display: flex;
      align-items: center;
      gap: 6px;
      .icon-position {
        color: #9b9faf;
        font-size: 17px;
      }
      span:nth-child(2) {
        font-size: 14px;
      }
      span:nth-child(3) {
        color: #9b9faf;
        font-size: 12px;
      }
    }
  }
}
// 高亮显示
::v-deep(.highlight) {
  color: #2c9eff;
}
</style>
